package cms.simmytech.service;

import cms.simmytech.mapper.*;
import cms.simmytech.model.*;
import cms.simmytech.util.DateUtil;
import cms.simmytech.vo.MenuFirstVo;
import cms.simmytech.vo.MenuSecondVo;
import cms.simmytech.vo.MenuThirdVo;
import cms.simmytech.vo.MenuVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.catalina.mapper.Mapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserService {

	@Autowired
	private SysUserMapper userMapper;
	@Autowired
	private SysRoleMapper roleMapper;
	@Autowired
	private SysPermissionMapper permissionMapper;
	@Autowired
	private SysPermissionRoleMapper permissionRoleMapper;
	@Autowired
	private SysRoleUserMapper roleUserMapper;
	@Autowired
	private SysUserBaseMapper sysUserBaseMapper;
	@Autowired
	private TbBaseMapper baseMapper;
	@Autowired
	private TbExaminerMapper examinerMapper;
//	后增
	@Autowired
	private TbUserMapper tbUserMapper;

	
	Log log=LogFactory.getLog(UserService.class);
	
	BCryptPasswordEncoder encode=new BCryptPasswordEncoder();
	private TbUser bean;

	public static void main(String[] args) {
		BCryptPasswordEncoder encode1=new BCryptPasswordEncoder();
		System.out.println(encode1.encode("123456"));
	}

	//后增方法
	public PageInfo<TbUser> getUserByUserName(int pageNum,int pageSize,String userName) {
		PageHelper.startPage(pageNum, pageSize);
		TbUserExample tbUserExample = new TbUserExample();
		TbUserExample.Criteria criteria = tbUserExample.createCriteria();
		criteria.andUserNameLike( userName );
//		criteria.
//		List<TbUser> list= tbUserMapper.selectByUserName( userName );
		List<TbUser> list= tbUserMapper.selectByExample( tbUserExample );
		PageInfo<TbUser> pageInfo=new PageInfo<>(list);
		return pageInfo;
	}
	public PageInfo<TbUser> getUserList1(Integer pageNum, Integer pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		TbUserExample example=new TbUserExample();
		example.setOrderByClause(" user_id  desc");
		List<TbUser> list= tbUserMapper.selectByExample(example);
		PageInfo<TbUser> pageInfo=new PageInfo<>(list);
		return pageInfo;
	}

//	tbuser删除
	public void deleteUser(int id) {

		tbUserMapper.deleteByPrimaryKey(id);
	}
////	tbuser保存目录
//	public void saveTbuser (TbUser bean) {
//		this.bean = bean;
//		if (bean.getUserId() == null) {
////			bean.setRecTime((int)(System.currentTimeMillis()/1000));
//			tbUserMapper.insertSelective(bean);
//		} else {
//			tbUserMapper.updateByPrimaryKeySelective(bean);
//		}
//	}
















	public SysUser getUserInfo(){
		UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		SysUser userBean = userMapper.findByUserName(userDetails.getUsername());
		return userBean;
	}
	
	public PageInfo<SysUser> getUserList(int pageNum, int pageSize) {
		PageHelper.startPage( pageNum, pageSize );
		SysUserExample example = new SysUserExample();
		example.setOrderByClause( " id  desc" );
		List<SysUser> list = userMapper.selectByExample( example );
		PageInfo<SysUser> pageInfo = new PageInfo<>( list );
		return pageInfo;
	}

	public SysUser getUser(int id) {
		return userMapper.selectByPrimaryKey(id);
	}

	public void updateUserLogintime(int id){
		SysUser bean=userMapper.selectByPrimaryKey(id);
		bean.setLastLoginTime((int)(System.currentTimeMillis()/1000));
		userMapper.updateByPrimaryKeySelective(bean);
	}
	
	public SysUser getUserByUserName(String username){
		return userMapper.findByUserName(username);
	}
	
	public void saveUser(SysUser bean, int roleId, Integer baseId, Integer projectId, String examinerName) {
		String   epass="";
		if(!StringUtils.isEmpty(bean.getPassword())){
			epass=bean.getPassword();
			bean.setPassword(encode.encode(bean.getPassword().trim()));
		}
		TbBase base = baseMapper.selectByPrimaryKey(baseId);
		if (bean.getId() == null) {
			bean.setCreateTime((int)(System.currentTimeMillis()/1000));
			bean.setUpdateTime((int)(System.currentTimeMillis()/1000));
			userMapper.insertSelective(bean);
			SysRoleUser roleUser=new SysRoleUser();
			roleUser.setSysRoleId(roleId);
			roleUser.setSysUserId(bean.getId());
			roleUserMapper.insertSelective(roleUser);
			SysRole sysRole = roleMapper.selectByPrimaryKey(roleId);
			SysUserBase  userBase=new SysUserBase();
			if (sysRole.getName().equals("ROLE_ADMIN")){
				userBase.setUid(bean.getId());
				userBase.setBaseId(0);
				userBase.setCreateTime(DateUtil.getIntStampTime());
				userBase.setBaseName("超级管理员");
				userBase.setBaseCode("0000");
			}else if (sysRole.getName().equals("ROLE_HOME")){
				userBase.setUid(bean.getId());
				userBase.setBaseId(baseId);
				userBase.setCreateTime(DateUtil.getIntStampTime());
				userBase.setBaseName(base.getBaseName());
				userBase.setBaseCode(base.getBaseCode());
			}else {
				userBase.setUid(bean.getId());
				userBase.setBaseId(baseId);
				userBase.setCreateTime(DateUtil.getIntStampTime());
				userBase.setBaseName(base.getBaseName());
				userBase.setBaseCode(base.getBaseCode());
				TbExaminer examiner=new TbExaminer();
				examiner.setBaseId(baseId);
				examiner.setExaminerName(examinerName);
				examiner.setProjectId(projectId);
				examiner.setBaseName(base.getBaseName());
				examiner.setBaseCode(base.getBaseCode());
				examiner.setUid(bean.getId());
				examiner.setExaminerPwd(epass);
				examiner.setExaminerCode(bean.getUsername());
				examinerMapper.insertSelective(examiner);

			}


			sysUserBaseMapper.insertSelective(userBase);
		} else {
			bean.setUpdateTime((int)(System.currentTimeMillis()/1000));
			userMapper.updateByPrimaryKeySelective(bean);
			SysRoleUserExample example=new SysRoleUserExample();
			example.createCriteria().andSysUserIdEqualTo(bean.getId());
			roleUserMapper.deleteByExample(example);
			SysRoleUser roleUser=new SysRoleUser();
			roleUser.setSysRoleId(roleId);
			roleUser.setSysUserId(bean.getId());
			roleUserMapper.insertSelective(roleUser);
			SysUserBase userBase = sysUserBaseMapper.selectByPrimaryKey(bean.getId());
			SysRole sysRole = roleMapper.selectByPrimaryKey(roleId);
			if (sysRole.getName().equals("ROLE_ADMIN")){
				userBase.setUid(bean.getId());
				userBase.setBaseId(0);
				userBase.setCreateTime(DateUtil.getIntStampTime());
				userBase.setBaseName("超级管理员");
				userBase.setBaseCode("0000");
			}else if (sysRole.getName().equals("ROLE_HOME")){
				userBase.setUid(bean.getId());
				userBase.setBaseId(baseId);
				userBase.setCreateTime(DateUtil.getIntStampTime());
				userBase.setBaseName(base.getBaseName());
				userBase.setBaseCode(base.getBaseCode());
			}else {
				userBase.setUid(bean.getId());
				userBase.setBaseId(baseId);
				userBase.setCreateTime(DateUtil.getIntStampTime());
				userBase.setBaseName(base.getBaseName());
				userBase.setBaseCode(base.getBaseCode());
				TbExaminerExample examinerexample=new TbExaminerExample();
				examinerexample.createCriteria().andUidEqualTo(bean.getId());
				TbExaminer examiner=new TbExaminer();
				List<TbExaminer> elist = examinerMapper.selectByExample(examinerexample);
				if (elist.size()>0)
					examiner=elist.get(0);
				examiner.setBaseId(baseId);
				examiner.setProjectId(projectId);
				examiner.setBaseName(base.getBaseName());
				examiner.setBaseCode(base.getBaseCode());
				examiner.setUid(bean.getId());
				examiner.setExaminerPwd(epass);
				examiner.setExaminerName(examinerName);
				examiner.setExaminerCode(bean.getUsername());
				if (elist.size()>0){
					examinerMapper.updateByPrimaryKeySelective(examiner);
				}else {
					examinerMapper.insertSelective(examiner);


				}

			}

			sysUserBaseMapper.updateByPrimaryKey(userBase);
		}
	}

	public boolean hasUserName(String userName) {
		SysUser bean = userMapper.findByUserName(userName);
		return bean == null ? false : true;
	}
	
	public boolean checkUserName(Integer id,String userName){
		boolean res=true;
		if(id==null){
			SysUser bean= userMapper.findByUserName(userName);
			if(bean!=null){
				return false;
			}
		}else{
			SysUser bean= userMapper.findByUserName(userName);
			if(bean!=null&&bean.getId().intValue()!=id){
				return false;
			}
		}
		return res;
	}

	public List<SysRole> getRoleList() {
		return roleMapper.selectByExample(null);
	}

	public SysRole getRole(int id) {
		return roleMapper.selectByPrimaryKey(id);
	}
	
	public int getRoleIdByUid(int uId){
		SysRoleUserExample example=new SysRoleUserExample();
		example.createCriteria().andSysUserIdEqualTo(uId);
		List<SysRoleUser> list=roleUserMapper.selectByExample(example);
		if(list.isEmpty()){
			return -1;
		}
		return list.get(0).getSysRoleId();
	}

	public SysRole getRoleByUid(int uid){
		SysRoleUserExample example=new SysRoleUserExample();
		example.createCriteria().andSysUserIdEqualTo(uid);
		List<SysRoleUser> list=roleUserMapper.selectByExample(example);
		if(!list.isEmpty()){
			return roleMapper.selectByPrimaryKey(list.get(0).getSysRoleId());
		}
		return null;
	}
	
	public void saveRole(SysRole bean, int[] permissionIds) {
		if (bean.getId() == null) {
			roleMapper.insertSelective(bean);
			SysPermissionRole prBean = null;
			for (int pid : permissionIds) {
				prBean = new SysPermissionRole();
				prBean.setRoleId(bean.getId());
				prBean.setPermissionId(pid);
				permissionRoleMapper.insertSelective(prBean);
			}
		} else {
			roleMapper.updateByPrimaryKeySelective(bean);
			SysPermissionRoleExample example=new SysPermissionRoleExample();
			example.createCriteria().andRoleIdEqualTo(bean.getId());
			permissionRoleMapper.deleteByExample(example);
			SysPermissionRole prBean = null;
			for (int pid : permissionIds) {
				prBean = new SysPermissionRole();
				prBean.setRoleId(bean.getId());
				prBean.setPermissionId(pid);
				permissionRoleMapper.insertSelective(prBean);
			}
		}
	}
	
	public List<SysPermissionRole> getRoleHas(int roleId){
		SysPermissionRoleExample example=new SysPermissionRoleExample();
		example.createCriteria().andRoleIdEqualTo(roleId);
		return permissionRoleMapper.selectByExample(example);
	}

	public int  deleteRole(int id) {
		SysRoleUserExample rlexample=new SysRoleUserExample();
		rlexample.createCriteria().andSysRoleIdEqualTo(id);
		List<SysRoleUser> list = roleUserMapper.selectByExample(rlexample);
		if (list.isEmpty()){
			roleMapper.deleteByPrimaryKey(id);
			SysPermissionRoleExample example=new SysPermissionRoleExample();
			example.createCriteria().andRoleIdEqualTo(id);
			permissionRoleMapper.deleteByExample(example);

			return   1;
		}
		return 0;
	}

	public List<SysPermission> getPermissionList(int pId) {
		
		
		SysPermissionExample example = new SysPermissionExample();
		example.createCriteria().andPidEqualTo(pId);
		example.setOrderByClause(" psort");
		return permissionMapper.selectByExample(example);
	}
	
	public List<SysPermission> getPermissionByUserId(int userId){
		return permissionMapper.findByAdminUserId(userId);
	}

	public SysPermission getPermission(int id) {
		return permissionMapper.selectByPrimaryKey(id);
	}

	public void savePermission(SysPermission bean) {
		if (bean.getId() == null) {
			bean.setPsort((int)(System.currentTimeMillis()/1000));
			permissionMapper.insertSelective(bean);
		} else {
			permissionMapper.updateByPrimaryKeySelective(bean);
		}
	}

	public void deletePermission(int id) {
		permissionMapper.deleteByPrimaryKey(id);
	}
	
	public boolean movePermission(int id,String type){
		SysPermission bean=permissionMapper.selectByPrimaryKey(id);
		if(type.equals("up")){
			SysPermissionExample example=new SysPermissionExample();
			example.createCriteria().andPsortLessThan(bean.getPsort()).andPidEqualTo(bean.getPid());
			example.setOrderByClause(" psort desc limit 1");
			List<SysPermission> list=permissionMapper.selectByExample(example);
			if(!list.isEmpty()){
				SysPermission bean1=list.get(0);
				permissionMapper.updatePsort(bean.getId(), bean1.getPsort());
				permissionMapper.updatePsort(bean1.getId(), bean.getPsort());
				return true;
			}
		}else if(type.equals("down")){
			SysPermissionExample example=new SysPermissionExample();
			example.createCriteria().andPsortGreaterThan(bean.getPsort()).andPidEqualTo(bean.getPid());
			example.setOrderByClause(" psort limit 1");
			List<SysPermission> list=permissionMapper.selectByExample(example);
			if(!list.isEmpty()){
				SysPermission bean1=list.get(0);
				permissionMapper.updatePsort(bean.getId(), bean1.getPsort());
				permissionMapper.updatePsort(bean1.getId(), bean.getPsort());
				return true;
			}
		}
		return false;
	}

	public MenuVo getMenuPage() {
		SysUser userBean = getUserInfo();
		List<SysPermission> baseList = permissionMapper.selectMenuPage(userBean.getId(), 0);
		MenuVo menuVo = new MenuVo();
		List<MenuFirstVo> firstList = new ArrayList<MenuFirstVo>();
		MenuFirstVo firstBean = null;
		for (SysPermission baseBean : baseList) {
			firstBean = new MenuFirstVo();
			firstBean.setId(baseBean.getId());
			firstBean.setDescritpion(baseBean.getDescritpion());
			firstBean.setUrl(baseBean.getUrl());
			firstBean.setName(baseBean.getName());
			firstBean.setLegend(baseBean.getLegend());
			List<SysPermission> base2List = permissionMapper.selectMenuPage(userBean.getId(), firstBean.getId());
			if (!base2List.isEmpty()) {
				List<MenuSecondVo> secondList = new ArrayList<>();
				MenuSecondVo secondBean = null;
				for (SysPermission base2Bean : base2List) {
					secondBean = new MenuSecondVo();
					secondBean.setId(base2Bean.getId());
					secondBean.setDescritpion(base2Bean.getDescritpion());
					secondBean.setUrl(base2Bean.getUrl());
					secondBean.setName(base2Bean.getName());
					List<SysPermission> base3List = permissionMapper.selectMenuPage(userBean.getId(),
							secondBean.getId());
					if (!base3List.isEmpty()) {
						List<MenuThirdVo> thirdList = new ArrayList<>();
						MenuThirdVo thirdBean = null;
						for (SysPermission base3Bean : base3List) {
							thirdBean = new MenuThirdVo();
							thirdBean.setId(base3Bean.getId());
							thirdBean.setDescritpion(base3Bean.getDescritpion());
							thirdBean.setUrl(base3Bean.getUrl());
							thirdBean.setName(base3Bean.getName());
							thirdList.add(thirdBean);
						}
						secondBean.setList(thirdList);
					}
					secondList.add(secondBean);
				}
				firstBean.setList(secondList);
			}
			firstList.add(firstBean);
		}
		menuVo.setList(firstList);
		return menuVo;
	}

	public List<SysPermission> getPermissionByUrl(String url) {
		SysPermissionExample example = new SysPermissionExample();
		example.createCriteria().andUrlEqualTo(url);
		return permissionMapper.selectByExample(example);
	}

	public List<SysRole> getRoleByPermissionId(int id) {
		return roleMapper.selectByPerId(id);
	}

	public List<SysPermission> getPermissionList() {
		SysPermissionExample example=new SysPermissionExample();
		example.setOrderByClause(" psort");
		return permissionMapper.selectByExample(null);
	}


	public SysUserBase getUserBase(Integer id) {
		 return  sysUserBaseMapper.selectByPrimaryKey(id);
	}

	public List<TbBase> getBaseList() {
		List<TbBase> list = baseMapper.selectByExample(null);
		return    list;
	}

    public TbBase getBase() {
		SysUser user = getUserInfo();
		SysUserBase userbase = getUserBase(user.getId());
		if(userbase.getBaseId().intValue()==0){
				TbBase  base=new TbBase();
				base.setBaseId(0);
				base.setBaseName("超级管理员");
				return  base;
		}else {
			TbBaseExample example=new TbBaseExample();
			example.createCriteria().andBaseIdEqualTo(userbase.getBaseId());
			List<TbBase> list = baseMapper.selectByExample(example);
			return  list.get(0);
		}

    }


}
